﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BrokerBase.Lib.Person;
using BrokerBase.Lib.Core;
using System.IO;
using Microsoft.Win32;
using NHibernate;
using Broker.View.PolicyView;


namespace Broker.View.PersonView
{
    /// <summary>
    /// PersonForm.xaml 的交互逻辑
    /// </summary>
    public partial class PersonForm
    {
        private IPerson person;

        private const int IMAGE_MAX_SIZE=int.MaxValue;

        private Action callBack;

        public PersonForm(IPerson person)
        {

            this.person = person;

            InitializeComponent();
            Loaded += new RoutedEventHandler(PersonForm_Loaded);
        }

        public PersonForm(IPerson person, Action callBack)
            : this(person)
        {
            this.callBack = callBack;
        }

        void PersonForm_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = person;

            if (person.Sex == SexType.Male)
                rbtMale.IsChecked = true;
            else
                rbtFmale.IsChecked = true;

            

            ViewPhoto();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (!Verify())
                return;

            person.Sex = rbtMale.IsChecked.Value ? SexType.Male : SexType.Fmale;

            try
            {
                ISession sess = LibGlobal.HbmSessionFactory.GetCurrentSession();

                IBaseService<Person> svr = new BaseService<Person>(LibGlobal.HbmSessionFactory.GetCurrentSession());

                svr.SaveOrUpdate(person as Person);

                if (callBack != null)
                {
                    callBack();
                }

                MessageBox.Show(string.Format("客户: {0} 保存成功!",person.Name));

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private bool Verify()
        {
            if(string.IsNullOrEmpty(person.Name))
            {
                MessageBox.Show("姓名不能为空","提示");
                return false;
            }

            if (person.Photo !=null && person.Photo.Count() > IMAGE_MAX_SIZE)
            {
                MessageBox.Show("相片尺寸太大,请重新选择一个相片！", "提示");
                return false;
            }

            using (ISession sess = LibGlobal.HbmSessionFactory.OpenSession())
            {
                Person p = sess.CreateQuery("from Person where Name = '" + person.Name + "'").UniqueResult<Person>();

                if (p != null && p.Id != (person as Person).Id)
                {
                    MessageBox.Show("客户名称:"+person.Name +"已经存在!", "提示");
                    return false;
                }
            }


            return true;
        }

        

        private void ViewPhoto()
        {
            if (person.Photo != null && person.Photo.Count() >0)
            {
                try
                {
                    BitmapImage bitImage = null;
                    MemoryStream ms = new MemoryStream(person.Photo);
                    bitImage = new BitmapImage();
                    bitImage.BeginInit();
                    bitImage.StreamSource = ms;
                    bitImage.EndInit();

                    imgPhoto.Source = bitImage;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误提示");
                }
            }
        }

        private void SetDefaultPhoto(SexType sexType)
        {
            try
            {
                string packUri = null;
                if (sexType == SexType.Male)
                    packUri = "pack://application:,,,/Broker.View;Component/images/user_male.png";
                else
                    packUri = "pack://application:,,,/Broker.View;Component/images/user_female.png";

                imgPhoto.Source = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void rbtMale_Checked(object sender, RoutedEventArgs e)
        {
            person.Sex = SexType.Male;
            if (person.Photo==null || person.Photo.Count() == 0)
                SetDefaultPhoto(person.Sex);

        }

        private void rbtFmale_Checked(object sender, RoutedEventArgs e)
        {
            person.Sex = SexType.Fmale;
            if (person.Photo == null || person.Photo.Count() == 0)
                SetDefaultPhoto(person.Sex);
        }

        private void imgPhoto_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                string fileName = null;

                OpenFileDialog dlg = new OpenFileDialog();
                dlg.FileName = "图片";
                
                dlg.DefaultExt = "*.jpg";
                dlg.Filter = "bmp文件(.bmp)|*.bmp|jpg文件(.jpg)|*.jpg|gif文件(.gif)|*.gif|png文件(.png)|*.png|ico文件(.ico)|*.ico";
                bool? result = dlg.ShowDialog();
                if (result!=null && result == true)
                {
                    fileName = dlg.FileName;
                    FileStream fs = File.OpenRead(fileName);
                    byte[] imageb = new byte[fs.Length];
                    fs.Read(imageb, 0, imageb.Length);
                    fs.Close();

                    person.Photo = imageb;
                    ViewPhoto();
                }
            }
        }

        private void tabScheme_Loaded(object sender, RoutedEventArgs e)
        {
            SchemeListPage page = new SchemeListPage(person);

            famScheme.Content = page;
        }

        private void tabRelation_Loaded(object sender, RoutedEventArgs e)
        {
            HumanRelationListPage page = new HumanRelationListPage(person);

            famRelation.Content = page;
        }
    }
}
